// pages/square/partDetail.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "麓客局", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: '',
      isShare: 0
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,

    authData: {
      authType: '0', //0表示使用登录弹窗  1表示使用完善昵称头像弹窗 2表示直接弹出头像昵称选择框
      authUsername: "false", //是否已经授权头像昵称
    },
    showLogin: false, //是否显示授权弹窗
    showWsInfoDom: false, //直接显示头像昵称弹窗
    showPrivacyFlag: app.globalData.showPrivacyFlag,

    forumList: [],
    otherInfo: [], //点赞评论收藏等信息
    commentId: 0,
    commentList: [], //评论列表
    commentNumber: 0, //评论数量
    bmList: [],
    isHeightMode: false,

    focusFlag: false,
    tipContent: '说点什么吧',
    userComment: "",

    commentType: 1, //1：评论  2：回复,
    sendObjUserId: '',
    commentId: 0, //当前读取到的最大评论id
    cid: 0, //回复的评论id
    taUserId: '', //回复openid
    czIndex: 0, //操作的数组下标

    openid: '',
    is_nickAndHead: 0,
    shareTitle: '',
    shareImg: '',
    id: 0,
    mySf: '',
    headerUrl: '',
    is_bm: 0,
    userId: ''
  },

  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },

  // 预览图片
  previewImage(e) {
    let {
      sources,
      index
    } = e.currentTarget.dataset
    sources.filter(i => {
      i.type = i.type == 2 ? 'video' : 'image'
      i.poster = i.imgUrl
    })
    console.log("sources:", sources)
    wx.previewMedia({
      sources,
      current: index
    })
  },

  // 视频加载完成，改变视频的宽高
  videometa(e) {
    var that = this;
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        //视频的高
        var height = e.detail.height;

        //视频的宽
        var width = e.detail.width;

        //算出视频的比例
        var proportion = height / width;

        //res.windowWidth为手机屏幕的宽。
        var windowWidth = res.windowWidth;

        //算出当前宽度下高度的数值
        height = proportion * windowWidth;
        that.setData({
          height,
          width: windowWidth
        });
      }
    })
  },

  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    wx.getImageInfo({
      src: e.currentTarget.dataset.sources[0],
      success: function (res) {
        console.log(res.width, res.height); // 这里获取的宽高是正确的
        res.height >= res.width && this.setData({
          isHeightMode: true
        })
      },
      fail: function (err) {
        console.log(err);
      }
    });
  },

  //保存用户填写的内容 同时伴随失去焦点
  commentIpt(e) {
    var userComment = e.detail.value;
    this.setData({
      userComment: userComment
    })

    console.log(userComment);
  },

  //初始化输入框状态
  cshInput() {
    var that = this;
    var content = that.data.userComment.trim();
    if (content == '') {
      that.setData({
        tipContent: "说点什么吧",
        cid: 0,
        taUserId: '',
        commentType: 1
      });
    }
  },

  //处理点击某条评论
  hfController(e) {
    var that = this;
    var cid = e.currentTarget.dataset.cid;
    var taUserId = e.currentTarget.dataset.tauserid;
    var index = e.currentTarget.dataset.index;
    var nickname = e.currentTarget.dataset.nickname;

    console.log(e.currentTarget.dataset);

    if (taUserId == that.data.userId) {
      //自己点了自己
      this.setData({
        focusFlag: true,
        cid: cid,
        sendObjUserId: taUserId,
        tipContent: "说点什么吧",
        commentType: 2,
        czIndex: index
      });
    } else {
      this.setData({
        focusFlag: true,
        cid: cid,
        sendObjUserId: taUserId,
        tipContent: "回复 " + nickname,
        commentType: 2,
        czIndex: index
      });
    }
  },

  //发表评论
  send() {
    var that = this;
    //判断用户是否完善了信息
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var userComment = this.data.userComment;
    if (userComment == "") {
      app.showTip("请输入您想说的内容");
      return;
    }

    //提交评论
    wx.showLoading({
      title: '评论发送中...'
    });

    wx.request({
      url: that.data.baseUrl + 'sendMsgGame.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.id,
        'content': userComment,
        'commentType': that.data.commentType,
        'sendObjUserId': that.data.sendObjUserId,
        'cid': that.data.cid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          if (that.data.commentType == 1) {
            //评论
            var commentList = that.data.commentList;
            var otherInfo = that.data.otherInfo;
            otherInfo[0].comment.num = parseInt(otherInfo[0].comment.num) + 1;
            commentList.unshift(res.data.info);
            that.setData({
              commentList: commentList,
              commentNumber: parseInt(that.data.commentNumber) + 1,
              otherInfo: otherInfo
            });
          } else {
            //回复
            var commentList = that.data.commentList;
            commentList[that.data.czIndex].hfList.push(res.data.info);
            that.setData({
              commentList: commentList
            });
          }
          that.setData({
            userComment: '',
            tipContent: '说点什么吧',
            focusFlag: false,
            cid: 0,
            sendObjUserId: '',
            commentType: 1,
            czIndex: 0
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });

  },


  //收藏
  collect(e) {
    var that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addScGame.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.otherInfo[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['otherInfo[' + index + '].collect.status']: "1",
              ['otherInfo[' + index + '].collect.num']: parseInt(that.data.otherInfo[index].collect.num) + 1
            })

          } else {
            that.setData({
              ['otherInfo[' + index + '].collect.status']: "0",
              ['otherInfo[' + index + '].collect.num']: parseInt(that.data.otherInfo[index].collect.num) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //点赞
  help(e) {
    var that = this;
    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '数据处理中...'
    });
    wx.request({
      url: that.data.baseUrl + 'addZanGame.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'id': that.data.otherInfo[index].id,
        'status': status
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          if (status == "0") {
            that.setData({
              ['otherInfo[' + index + '].help.status']: "1",
              ['otherInfo[' + index + '].help.num']: parseInt(that.data.otherInfo[index].help.num) + 1
            })

          } else {
            that.setData({
              ['otherInfo[' + index + '].help.status']: "0",
              ['otherInfo[' + index + '].help.num']: parseInt(that.data.otherInfo[index].help.num) - 1
            })
          }
        } else {
          app.showTip(res.data.msg);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //处理完善信息
  addWxInfo() {
    this.setData({
      ['authData.authType']: 1,
      showLogin: true
    });
  },

  //接收子组件电话授权及头像昵称授权后后返回的值
  returnVal(e) {

    //授权完头像昵称
    this.setData({
      is_nickAndHead: e.detail.is_nickAndHead
      //['userInfo.head']: e.detail.head,
      //['userInfo.nickname']: e.detail.nickname
    });

    app.showTip('个人信息已完善');
  },

  //点击我要报名
  goBm() {
    var that = this;
    //判断是否有报名资格
    if (that.data.forumList[0].is_yz_bm == 1 && that.data.mySf == '游客') {
      app.showTip('抱歉,此组局仅限业主参与哦');
      return;
    }

    //判断是否参与过此组局了
    if (that.data.is_bm == 1) {
      app.showTip('抱歉,您已经报名过此组局了哦');
      return;
    }

    //判断报名是否已经结束了
    if (that.data.forumList[0].is_end == 1) {
      app.showTip('抱歉,此组局已经结束了哦');
      return;
    }

    //跳转至报名界面
    that.addHeaderUrl();
    wx.redirectTo({
      url: '/pages/square/partyBm?id=' + that.data.id
    });
  },

  //点击头像跳转至发起者个人主页
  goOtherDetail(e) {
    var that = this;
    var userId = e.currentTarget.dataset.userid;
    var openid = e.currentTarget.dataset.openid;
    var flag = e.currentTarget.dataset.flag;
    if (flag == 1 || flag == '1') {
      //缓存跳转至麓客局
      wx.setStorageSync('listType', 1);
    }
    //判断是否是自己的主页
    if (userId == this.data.userId) {
      //跳自己的主页
      that.addHeaderUrl();
      wx.redirectTo({
        url: '/pages/square/my'
      });
    } else {
      that.addHeaderUrl();
      //跳别人的主页
      wx.redirectTo({
        url: '/pages/square/ta?userId=' + userId + "&openid=" + openid
      });
    }
  },

  //将回跳url写入缓存
  addHeaderUrl() {
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array) {
      if (this.data.headerUrl == headerUrlList[headerUrlList.length - 1]) {
        //与上一个回跳链接相同则不添加
        return;
      }
      headerUrlList.push(this.data.headerUrl);
      wx.setStorageSync('headerUrlList', headerUrlList);
    } else {
      headerUrlList = [];
      headerUrlList.push(this.data.headerUrl)
      wx.setStorageSync('headerUrlList', headerUrlList);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    var id = options.id;
    var is_share = options.is_share;
    //is_share = 1;
    //id = 3;
    if (id == null || id == 0 || isNaN(id) || id == undefined) {
      app.showTip('抱歉,未获取到组局id哦');
      setTimeout(function () {
        wx.switchTab({
          url: '/pages/square/index'
        });
      }, 2000);
      return;
    } else {
      that.setData({
        id: id
      });
    }

    //赋值回跳本页的url
    if (is_share == 1) {
      that.setData({
        ['defaultData.isShare']: 1
      });
    } else {
      that.setData({
        headerUrl: '/pages/square/partDetail?id=' + id
      });
    }

    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    } else {
      wx.setStorageSync('listType', 1);
      that.setData({
        ['defaultData.goUrl']: '/pages/square/index'
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getGameDetailPageInfo(res.data.openid, id);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getGameDetailPageInfo(openid, id);
    }

    //调用分享
    //that.getShareInfo();

  },

  //获取本页数据
  getGameDetailPageInfo(openid, id) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getGameDetailPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        id: id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            mySf: res.data.mySf,
            forumList: res.data.gameInfo,
            bmList: res.data.bmList,
            is_bm: res.data.is_bm,

            otherInfo: res.data.forumList,
            is_nickAndHead: res.data.is_nickAndHead,
            commentId: res.data.commentId,
            commentList: res.data.commentList,
            commentNumber: res.data.commentNum,

            shareTitle: res.data.gameInfo[0].title,
            shareImg: that.data.baseUrl + res.data.gameInfo[0].mediaList[0].img_path,
            userId: res.data.userId
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/partDetail?id=' + that.data.id,
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})